using MediatR;
using RBAC_Class.Domain;
using RBAC_Class.ErrorCode;
using RBAC_Class.Infrastructrue.Interfaces;
using RBAC_Class.Write.API.Application.Command.Users;
using System;
using NLog;

namespace RBAC_Class.Write.API.Application.CommandHandler.Users
{
    public class DeleteUserCommandHandler : IRequestHandler<DeleteUserCommand, APIResult<int>>
    {
        private readonly IBaseRepository<User> userRep;
        private readonly IBaseRepository<UserRole> userRoleRep;
        private readonly ILogger<DeleteUserCommandHandler> logger;

        public DeleteUserCommandHandler(IBaseRepository<User> userRep, IBaseRepository<UserRole> userRoleRep, ILogger<DeleteUserCommandHandler> logger)
        {
            this.userRep = userRep;
            this.userRoleRep = userRoleRep;
            this.logger = logger;
        }

        public Task<APIResult<int>> Handle(DeleteUserCommand request, CancellationToken cancellationToken)
        {
            try
            {
                var user = userRep.GetAll().FirstOrDefault(x => x.UserID == request.UserID && x.IsDelete == false);
                if (user == null)
                {
                    return Task.FromResult(new APIResult<int> { Code = ResultCode.Fail, Message = "用户不存在" });
                }
                user.IsDelete = true;
                userRep.Update(user);

                var userRoles = userRoleRep.GetAll().Where(x => x.UserID == request.UserID && x.IsDelete == false).ToList();
                foreach (var ur in userRoles)
                {
                    ur.IsDelete = true;
                    userRoleRep.Update(ur);
                }
                return Task.FromResult(new APIResult<int> { Code = ResultCode.Success, Message = "删除成功", Data = user.UserID });
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "删除用户失败 - 用户ID: {UserID}", request.UserID);
                throw;
            }
        }
    }
} 